package com.mobile.check.activitys;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;

import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.kit.NLog;
import cn.droidlover.xdroidmvp.kit.NToast;
import cn.droidlover.xdroidmvp.mvp.XActivity;
import com.mobile.check.app.R;
import com.mobile.check.bluetooth.BluetoothSppClient;
import com.mobile.check.dialogs.CheckTipDialog;
import com.mobile.check.present.CheckBackGroundPresent;
import com.mobile.check.util.AppContents;
import com.mobile.check.util.DoubleUtil;
import com.mobile.check.views.MyTextView;

/**
 * 类名: CheckBackgroundActivity
 * 作者: 李学伟
 * 日期: 2020年10月14日 09:44
 * 描述:
 */
public class CheckBackgroundActivity extends XActivity<CheckBackGroundPresent> {
    @BindView(R.id.check1Tv)
    MyTextView check1Tv;
    @BindView(R.id.check2Tv)
    MyTextView check2Tv;
    @BindView(R.id.check3Tv)
    MyTextView check3Tv;
    @BindView(R.id.check4Tv)
    MyTextView check4Tv;
    @BindView(R.id.check5Tv)
    MyTextView check5Tv;
    //    BluetoothSppClient client;
    String mMac;
    CheckTipDialog checkTipDialog;
    MyTextView targetView;
    boolean mbThreadStop = false;
    protected BluetoothSppClient mBSC = null;
    String backgroudMark;

    @Override
    public void initView() {
        super.initView();
        titleTv.setText("背景检测");
        check1Tv.setValue(SharedPref.getInstance(this).getString(backgroudMark+"1","0.0"));
        check2Tv.setValue(SharedPref.getInstance(this).getString(backgroudMark+"2","0.0"));
        check3Tv.setValue(SharedPref.getInstance(this).getString(backgroudMark+"3","0.0"));
        check4Tv.setValue(SharedPref.getInstance(this).getString(backgroudMark+"4","0.0"));
        check5Tv.setValue(SharedPref.getInstance(this).getString(backgroudMark+"5","0.0"));
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mBSC = GlobalPoolApplication.instance.mBSC;
    }


    @Override
    public void getDataFromServer() {

    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_checkbackground;
    }

    @Override
    public void getIntentData() {
        backgroudMark = getIntent().getStringExtra("backgroudMark");
    }

    @Override
    public CheckBackGroundPresent newP() {
        return new CheckBackGroundPresent();
    }

    public static void lunch(Activity activity, String backgroudMark) {
        Intent intent = new Intent(activity, CheckBackgroundActivity.class);
        intent.putExtra("backgroudMark", "backgroudMark");
        activity.startActivityForResult(intent, 0x002);
    }

    @OnClick({R.id.check1Btn, R.id.check2Btn, R.id.check3Btn, R.id.check4Btn, R.id.check5Btn, R.id.submitBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.check1Btn:
                targetView = check1Tv;
                startTest();
                break;
            case R.id.check2Btn:
                targetView = check2Tv;
                startTest();
                break;
            case R.id.check3Btn:
                targetView = check3Tv;
                startTest();
                break;
            case R.id.check4Btn:
                targetView = check4Tv;
                startTest();
                break;

            case R.id.check5Btn:
                targetView = check5Tv;
                startTest();
                break;
            case R.id.submitBtn:
                String backgroundValue = getValue();
                SharedPref.getInstance(this).putString(backgroudMark+"1",check1Tv.getValue());
                SharedPref.getInstance(this).putString(backgroudMark+"2",check2Tv.getValue());
                SharedPref.getInstance(this).putString(backgroudMark+"3",check3Tv.getValue());
                SharedPref.getInstance(this).putString(backgroudMark+"4",check4Tv.getValue());
                SharedPref.getInstance(this).putString(backgroudMark+"5",check5Tv.getValue());
                Intent intent = new Intent();
                intent.putExtra("backgroundValue", backgroundValue);
                setResult(Activity.RESULT_OK, intent);
                finish();
                break;
        }

    }


    private void startTest() {
        boolean isConnect = GlobalPoolApplication.instance.isConnect();
        if (!isConnect) {
            NToast.shortToast(this, "当前设备未连接");
            return;
        } else {
            checkTipDialog = new CheckTipDialog(this, new CheckTipDialog.SlectClickListener() {
                @Override
                public void submitClick(String maxValue) {
                    mbThreadStop = true;
                    if (!TextUtils.isEmpty(maxValue)) {
                        targetView.setValue(maxValue);
                    }
                    if (AppContents.ISTEST) {
                        targetView.setValue("1.2");
                    }
                }
            });
            checkTipDialog.display();
            new receiveTask()
                    .executeOnExecutor(GlobalPoolApplication.instance.FULL_TASK_EXECUTOR);
        }
    }


    private String getValue() {
        double val = (Double.valueOf(check1Tv.getValue())
                + Double.valueOf(check2Tv.getValue())
                + Double.valueOf(check3Tv.getValue())
                + Double.valueOf(check4Tv.getValue()) + Double
                .valueOf(check5Tv.getValue())) / 5;
        BigDecimal bg = new BigDecimal(val);
        double result = 0;
        try {
            result = DoubleUtil.getDouble(val, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(result);
    }

    private String getValueStr() {
        StringBuilder builder = new StringBuilder();
        builder.append(check1Tv.getValue()).append(",");
        builder.append(check2Tv.getValue()).append(",");
        builder.append(check3Tv.getValue()).append(",");
        builder.append(check4Tv.getValue()).append(",");
        builder.append(check5Tv.getValue());
        return builder.toString();
    }

    @Override
    public boolean isNotWorkConnect() {
        return false;
    }

    @Override
    protected void onDestroy() {
        mbThreadStop = true;
        super.onDestroy();
    }


    /*多线程处理(建立蓝牙设备的串行通信连接)*/
    private class receiveTask extends AsyncTask<String, String, Integer> {
        /**
         * Constant: the connection is lost
         */
        private final static byte CONNECT_LOST = 0x01;
        /**
         * Constant: the end of the thread task
         */
        private final static byte THREAD_END = 0x02;

        /**
         * 线程启动初始化操作
         */
        @Override
        public void onPreExecute() {
            mbThreadStop = false;
        }

        /**
         * 线程异步处理
         */
        @Override
        protected Integer doInBackground(String... arg0) {
            mBSC.Receive(); //首次启动调用一次以启动接收线程
            while (!mbThreadStop) {
                if (!mBSC.isConnect())//检查连接是否丢失
                    return (int) CONNECT_LOST;

                if (mBSC.getReceiveBufLen() > 0) {
                    SystemClock.sleep(20); //先延迟让缓冲区填满
                    this.publishProgress(mBSC.Receive());
                }
                NLog.d("receiveTask", TAG + "接收数据");
            }
            return (int) THREAD_END;
        }

        /**
         * 线程内更新处理
         */
        @Override
        public void onProgressUpdate(String... progress) {
            if (null != progress[0]) {
                String value = progress[0];
                String reveiveData = value.replaceAll("OK", "").trim();
                reveiveData = reveiveData.replace(" ", "");
                reveiveData = reveiveData.replace(" ", "");
                reveiveData = reveiveData.replace("\r", "");
                reveiveData = reveiveData.replace("\n", "");
                try {
                    float receive = Float.parseFloat(reveiveData);
                    checkTipDialog.setReceiveDatas(receive);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * 阻塞任务执行完后的清理工作
         */
        @Override
        public void onPostExecute(Integer result) {
            if (CONNECT_LOST == result) //connection is lost
                NToast.shortToast(getString(R.string.msg_msg_bt_connect_lost));
            else {
//                NToast.shortToast(getString(R.string.msg_receive_data_stop));
            }
        }
    }

}
